﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using Windows.Devices.PointOfService;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace WellDone
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    /// 

    public sealed partial class BlacklineDialog : Page
    {
        public event EventHandler CloseRequested;
        public string strAuthCode = "";

        public BlacklineDialog()
        {
            this.InitializeComponent();
        }

        public async Task<bool> processSale(decimal in_amount, int in_invoice)
        {
            // Call the eConduit REST web service to run the transaction
//            string requestUrl = "https://econduitapp.com/services/api.asmx/runTransaction?command=sale&key=5c11ad88-6929-405f-b27a-318716e64527&password=dd6679a4-60bd-45f3-ad06-5dd18aed974b&Amount=20.00&terminalID=4493&refId=1004";
            string requestUrl = Globals.strBlacklineUrl + "/runTransaction?command=sale&key=" + Globals.strBlacklineKey + "&password=" + Globals.strBlacklinePassword + "&Amount=" + in_amount.ToString() + "&terminalID=" + Globals.strBlacklineTerminalID + "&refId="+in_invoice.ToString();
            bool bResult = false;
            BlacklineJsonResponse jsonResponse;
            try
            {
                HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
                HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
                System.Diagnostics.Debug.WriteLine(response.Headers.ToString());
                if (response.StatusCode != HttpStatusCode.OK)
                    throw new Exception(String.Format(
                    "Server error (HTTP {0}: {1}).",
                    response.StatusCode,
                    response.StatusDescription));
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(BlacklineJsonResponse));
                object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                jsonResponse = objResponse as BlacklineJsonResponse;
                System.Diagnostics.Debug.WriteLine(jsonResponse.ResultCode);
                System.Diagnostics.Debug.WriteLine(jsonResponse.Message);
                System.Diagnostics.Debug.WriteLine(jsonResponse.RefID);
                // If the transaction was approved, update the database...
                if (jsonResponse.ResultCode == "Approved")
                {
                    ServiceReferenceOpenRPOS.Blackline blackline_rec = new ServiceReferenceOpenRPOS.Blackline();
                    blackline_rec.bFilterAuthCode = true;
                    blackline_rec.bFilterCardType = true;
                    blackline_rec.bFilterLast4 = true;
                    blackline_rec.bFilterName = true;
                    blackline_rec.bFilterOrderCheckID = true;
                    blackline_rec.bFilterResultCode = true;
                    blackline_rec.bFilterTransType = true;
                    blackline_rec.col_AuthCode = jsonResponse.AuthCode;
                    blackline_rec.col_CardType = jsonResponse.CardType;
                    blackline_rec.col_Last4 = jsonResponse.Last4;
                    blackline_rec.col_Name = jsonResponse.Name;
                    blackline_rec.col_ResultCode = jsonResponse.ResultCode;
                    blackline_rec.col_TransType = jsonResponse.TransType;
                    blackline_rec.col_OrderCheckID = in_invoice;
                    await Globals.client.AddBlacklineObjectAsync(Globals.token, blackline_rec);
                    strAuthCode = jsonResponse.AuthCode;
                    // Update the order check...
                    ServiceReferenceOpenRPOS.OrderCheck oc = new ServiceReferenceOpenRPOS.OrderCheck();
                    oc.col_ID = in_invoice;
                    oc.bFilterAuthCode = true;
                    oc.col_AuthCode = jsonResponse.AuthCode;
                    await Globals.client.UpdateOrderCheckObjectAsync(Globals.token, oc);
                    bResult = true;
                }
                // Update the message text...
                tbMessage.Text = jsonResponse.ResultCode;
                btnClose.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                // Update the message text...
                tbMessage.Text = ex.Message;
                btnClose.Visibility = Visibility.Visible;
            }
            return bResult;
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.CloseRequested != null)
            {
                this.CloseRequested(this, EventArgs.Empty);
            }
        }
    }

    [DataContract]
    public class BlacklineJsonResponse
    {
        [DataMember(Name = "ResultCode")]
        public string ResultCode { get; set; }
        [DataMember(Name = "AuthCode")]
        public string AuthCode { get; set; }
        [DataMember(Name = "TransType")]
        public string TransType { get; set; }
        [DataMember(Name = "Amount")]
        public decimal Amount { get; set; }
        [DataMember(Name = "GiftCardBalance")]
        public decimal GiftCardBalance { get; set; }
        [DataMember(Name = "CardType")]
        public string CardType { get; set; }
        [DataMember(Name = "Last4")]
        public string Last4 { get; set; }
        [DataMember(Name = "Name")]
        public string Name { get; set; }
        [DataMember(Name = "Message")]
        public string Message { get; set; }
        [DataMember(Name = "RefID")]
        public string RefID { get; set; }
    }


}
